package spring.tx.config.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * description: 配置类，创建数据库连接池Druid、JdbcTemplate
 *
 * 1. @Configuration
 * 2. @ComponentScan("")
 * 3. @PropertySource("")
 * 4. @EnableAspectJAutoProxy() //开启aspectj注解的支持
 * 5. @EnableTransactionManagement //开启事务注解的支持
 * 6. @Bean // 将第三方类引入IOC容器
 * 7. 引用其他同样被@Bean注释的组件时，可以直接通过形参调用，或通过调用对应的方法名获取组件
 */

@Configuration
@ComponentScan("spring.tx")
@PropertySource("classpath:jdbc.properties")
@EnableAspectJAutoProxy
@EnableTransactionManagement
public class JavaConfig {

    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    //druid连接池
    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    //jdbcTemplate
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource){
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

    //事务操作JDBC实现类，需要连接池对数据库进行事务操作
    @Bean
    public TransactionManager transactionManager(DataSource dataSource){
        //内部要进行事务的操作
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        //需要连接池对象
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }
}
